#!/bin/bash
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Runs Chrome / content_shell and attaches to the first renderer process in gdb.

RENDERER_PID_RE='Renderer \(([0-9]+)\) paused waiting for debugger'
DEFAULT_TARGET_FLAGS=(--no-sandbox --renderer-startup-dialog)
TARGET=$1
shift

if [ -z "$TARGET" ]; then
  echo "usage: $(basename $0) <path-to-content-shell> [more-args...]"
  exit 1
fi

SAW_DISABLE_FEATURES=false
for TARGET_FLAG in "$@"; do
  if [[ "$TARGET_FLAG" == "--disable-features="* ]]; then
    TARGET_FLAG="$TARGET_FLAG,SpareRendererForSitePerProcess"
    SAW_DISABLE_FEATURES=true
  fi
  TARGET_FLAGS+=("$TARGET_FLAG")
done
if [ $SAW_DISABLE_FEATURES != true ]; then
  DEFAULT_TARGET_FLAGS+=(--disable-features=SpareRendererForSitePerProcess)
fi
TARGET_FLAGS=(${DEFAULT_TARGET_FLAGS[@]} ${TARGET_FLAGS[@]})

if [ -z "$DEBUGGER" ]; then
  if which lldb > /dev/null; then
    DEBUGGER="lldb"
    CONTINUE="continue"
  elif which gdb > /dev/null; then
    DEBUGGER="gdb -q"
    CONTINUE="signal SIGUSR1"
  else
    echo "no debugger found"
    exit 1
  fi
fi

OUTPUT=$(mktemp "${TMPDIR:-/tmp}"/"$(basename $0)".XXXXX)
trap "rm $OUTPUT" EXIT
echo "$TARGET" ${TARGET_FLAGS[@]} >&2
"$TARGET" ${TARGET_FLAGS[@]} > >(tee $OUTPUT) 2>&1 &
BROWSER_PID=$!

wait_renderer_pid() {
  for i in {1..100}; do
    browser_running || return
    RENDERER_PID=$(renderer_pid)
    [ -n "$RENDERER_PID" ] && return
    sleep 0.2
  done
}

browser_running() { ps -p $BROWSER_PID > /dev/null; }
renderer_pid() { [[ "$(cat $OUTPUT)" =~ $RENDERER_PID_RE ]] && echo ${BASH_REMATCH[1]}; }

wait_renderer_pid
if [ -n "$RENDERER_PID" ]; then
  # print yellow message
  echo -e "\n\033[1;33mDebugging renderer, use '$CONTINUE' to run.\033[0m\n"
  $DEBUGGER -p $RENDERER_PID
fi

wait
